﻿using System;
using System.Diagnostics;
using System.Speech.Synthesis;

namespace Ellanet.Wrappers
{
    static class SpeechWrapper
    {
        public static int Rate { get; set; }

        public static string Voice { get; set; }

        private static SpeechSynthesizer _speech;

        public static void Say(string dialogue, bool force)
        {
            try
            {
                ConfigureSpeech();
                if (force) _speech.SpeakAsyncCancelAll();
                _speech.Speak(dialogue);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public static void SayAsync(string dialogue, bool force)
        {
            try
            {
                ConfigureSpeech();
                if (force) _speech.SpeakAsyncCancelAll();
                _speech.SpeakAsync(dialogue);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        private static void ConfigureSpeech()
        {
            try
            {
                if (_speech == null)
                {
                    _speech = new SpeechSynthesizer();
                    _speech.SetOutputToDefaultAudioDevice();
                }

                if ((Rate <= 10) && (Rate >= -10)) _speech.Rate = Rate;
                if (Voice != null) _speech.SelectVoice(Voice);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
    }
}
